package com.kandinfo.base.common.util.web;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.kandinfo.base.common.util.PageEnumSerializer;
import com.kandinfo.base.security.xss.XssSantizeJsonSerializer;

import eu.bitwalker.useragentutils.DeviceType;
import eu.bitwalker.useragentutils.UserAgent;

/**
 * Class Name: WebUtil 
 * 
 * @author SC
 * 
 */
public final class WebUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebUtil.class);
    private static ObjectMapper objectMapper;
    private WebUtil() {

    }

    

    
    /**
    * Description: get the current request bound to current thread
    *
    * @return
    */
    public static HttpServletRequest getThreadRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    
    /**
    * Description: get the current session bound to current thread
    *
    * @return
    */
    public static HttpSession getThreadSession() {
        return getThreadRequest().getSession(true);
    }

    
    /**
    * Description: determine whether current request is sent via AJAX
    *
    * @return
    */
    public static boolean isAjaxRequest() {
        return isAjaxRequest(getThreadRequest());
    }

    
    /**
    * Description: determine whether given request is sent via AJAX
    *
    * @param request
    * @return
    */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("X-Requested-With");
        return requestedWith != null ? "XMLHttpRequest".equals(requestedWith) : false;
    }

    
    /**
    * Description: get the full URL for a relative path
    *
    * @param path
    * @return
    */
    public static String getFullUrlBasedOn(String path) {
        StringBuilder targetUrl = new StringBuilder();
        if (path.startsWith("/")) {
            // Do not apply context path to relative URLs.
            targetUrl.append(getThreadRequest().getContextPath());
        }
        targetUrl.append(path);
        return targetUrl.toString();
    }

    
    /**
    * Description: get the {@link ObjectMapper} that will be used in converter.
    *
    * @return
    */
    @SuppressWarnings("deprecation")
    public static ObjectMapper getObjectMapper() { // NOSONAR
        if (objectMapper == null) {
            synchronized(WebUtil.class) {
                if (objectMapper == null) {
                    objectMapper = new ObjectMapper();
                    SimpleModule module = new SimpleModule("Custom Serializer", new Version(1, 0, 0, "FINAL"));
                    module.addSerializer(new XssSantizeJsonSerializer());
                    module.addSerializer(new PageEnumSerializer());
                    objectMapper.registerModule(module);
                }
            }
        }
        return objectMapper;
    }
    
    public static String getConsumerIp() {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            return addr.getHostAddress();//返回本机ip
        } catch (UnknownHostException e) {
            LOGGER.error("WebUtil.getConsumerIp()获取失败！", e);
        }
        return null;
    }

    /**
     * 
     * 判断联机设备
     * 
     * @return 	MOBILE COMPUTER ....
     */
    public static String checkDeviceType() {
		HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
   		UserAgent userAgent = UserAgent.parseUserAgentString(req.getHeader("User-Agent"));
   		DeviceType deviceType=userAgent.getOperatingSystem().getDeviceType();
   		return deviceType.name();
		
	}

    
}
